class QuarkImage < ActiveRecord::Base
  has_attachment :content_type => :image,
    :storage => :file_system,
    :max_size => 400.kilobytes,
    :resize_to => '400x400>',
    :thumbnails => { :thumb => '50x50>' },
    :processor => 'ImageScience'

  validates_as_attachment

  belongs_to :quark

  #The block will be executed just before the thumbnail is saved.
  #We need to set extra values in the thumbnail class as
  #we want it to have the same extra attribute values as the original image
  #except for the default flag that is always set to false
  before_thumbnail_saved do |record, thumbnail|
    thumbnail.quark_id = record.quark_id
  end

  def source_url=(url)
    return nil if not url
    http_getter = Net::HTTP
    uri = URI.parse(url)
    response = http_getter.start(uri.host, uri.port) {|http|
      http.get(uri.path)
    }
    case response
    when Net::HTTPSuccess
      file_data = response.body
      return nil if file_data.nil? || file_data.size == 0
      self.content_type = response.content_type
      self.temp_data = file_data
      self.filename = uri.path.split('/')[-1]
    else
      return nil
    end
  end
end
